
import { getProfile, login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      // 持久化存储 localStorage / cookie
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    }
  },
  actions: {
    async login(context, data) {
      // TODO 调用登录接口
      const token = await login(data)
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const result = await getProfile()
      context.commit('setUserInfo', result)
    },
    // 退出登录的action
    logout(context) {
      context.commit('removeToken') // 删除token
      context.commit('setUserInfo', {}) // 设置用户信息为空对象
    }

  }
}
